<?php

namespace App\Http\Middleware;

use Closure;
use Session;
use DB;
use Illuminate\Database;

class AuthMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     * 暂时先不用
     */
    private $noLogin = ['login', 'register','error'];
    //未登录状态下才可以访问的路由
    private $auth = ['index','error'];
    //不需要验证权限的路由
    public function handle($request, Closure $next)
    {
        $path = $request->path();
        $user = Session::get('oaHome');
        //如果访问的是noLogin里的方法
        if (in_array($path, $this->noLogin) && !empty($user)) {
            //调用自定义跳转方法，跳到首页
            return errorRedirect(route('index'), '您已经登录，3秒钟后将跳转到首页！');
        }elseif (in_array($path, $this->noLogin) && empty($user)) {
            //调用自定义跳转方法，跳到首页
            return $next($request);
        }elseif (!in_array($path, $this->noLogin) && empty($user)) {
            //强制登录
            return errorRedirect(route('login'), '请先登录后再继续后面的操作！');
        }
        if (!in_array($path, $this->auth))
        {
            //如果访问的路由不在auth当中则需要验证rbac
            if(!$this->isAuth($user['id'],$path))
            {
                return errorRedirect(route('index'), '没有权限访问，即将跳转到首页！');
            }
        }
        return $next($request);
    }

    //传递过来的
    private function isAuth($uid, $route)
    {
        $user = DB::table('user')
            ->leftjoin('user_role','user.id','=','user_role.uid')
            ->leftjoin('role','role.id','=','user_role.rid')
            ->leftjoin('role_permission','role.id','=','role_permission.rid')
            ->leftjoin('permission','permission.id','=','role_permission.pid')
            ->groupBy('permission.id')
            ->where('user.id','=',$uid)
            ->where('permission.node','=',$route)
            ->get();
        if(count($user)>0)
        {
            return true;
        }
        return false;
    }
}
